package com.gopay.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.ResourceBundle;

public class ReadingPropertyFiles {
	public static void main(String[] args) {
		try {
			String merIdes = getPropertyElementByKey("payChannelSelect_PayWays", "merIdes");
			System.out.println(merIdes);
			
			System.out.println(getPropertyElementByKeyFromProperties("payChannelSelect_PayWays", "merIdes"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 通过Properties配置文件名称获取ResourceBundle对象
	 * @param propertyFileNameAsPackage：Properties配置文件名称，不含.properties后缀，含包路径！
	 * @return
	 * @throws Exception
	 */
	public static ResourceBundle getProperty2ResourceBundle(String propertyFileNameAsPackage) throws Exception{
		return ResourceBundle.getBundle(propertyFileNameAsPackage);
	}
	
	/**
	 * 通过key值直接获取Properties配置文件中key对应的value值
	 * @param propertyFileNameAsPackage：Properties配置文件名称，不含.properties后缀，含包路径！
	 * @param elementKey：key值
	 * @return
	 * @throws Exception
	 */
	public static String getPropertyElementByKey(String propertyFileNameAsPackage, String elementKey) throws Exception{
		return ResourceBundle.getBundle(propertyFileNameAsPackage).getString(elementKey);
	}

	/**
	 * 通过文件的绝对路径获取Properties对象
	 * @param propertyFileURL：Properties配置文件名称，含.properties后缀，含包路径。
	 * @return
	 * @throws Exception
	 */
	public static Properties getProperty2Properties(String propertyFileNameAsPackage) throws Exception{
		InputStream inputStream = null;
		Properties prop = new Properties();
		try {
			inputStream = new FileInputStream(new File(propertyFileNameAsPackage));
			prop.load(inputStream);
			inputStream.close();
			return prop;
		} finally {
			// /注意：不要忘记关闭输出流
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 通过key值直接获取Properties配置文件中key对应的value值
	 * @param propertyFileURL：Properties配置文件名称，含.properties后缀，含包路径。
	 * @param elementKey：key值
	 * @return
	 * @throws Exception
	 */
	public static String getPropertyElementByKeyFromProperties(String propertyFileNameAsPackage, String elementKey) throws Exception{
			return getProperty2Properties(propertyFileNameAsPackage).getProperty(elementKey);
	}
}
